package com.flute.framework.monitor;

import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.SerializableEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import com.flute.framework.configuration.MonitorXMLConverter;
import com.flute.framework.exception.ConfigurationParseException;
import com.flute.framework.exception.MonitorRegisterException;
import com.flute.tools.timer.IntervalExecutor;
import com.flute.tools.util.ExceptionUtil;

public class MonitorService {

	private IntervalExecutor executor;
	private MonitorDefinition definition;

	public MonitorService(InputStream stream)
			throws ConfigurationParseException {
		this.definition = MonitorXMLConverter.getMonitorDefinition(stream);
		this.executor = getIntervalExecutor();
		this.executor.setName("RegiterMonitor");
		this.executor.setInterval(definition.getRegisterInterval());
		FileHierarchy.setPath(definition.getLocation());
	}

	public void start() {
		executor.execute();
	}

	public MonitorDefinition getDefinition() {
		return definition;
	}

	public void setDefinition(MonitorDefinition definition) {
		this.definition = definition;
	}

	private IntervalExecutor getIntervalExecutor() {
		return new IntervalExecutor() {
			@Override
			public void execute() {
				for (Category cate : definition.getCategories()) {
					HttpEntity entity;
					try {
						entity = new SerializableEntity(cate, false);
						HttpPost post = new HttpPost(definition.getMonitorUrl());
						post.setEntity(entity);
						HttpClient httpclient = new DefaultHttpClient();
						httpclient.execute(post);
					} catch (Exception e) {
						throw new MonitorRegisterException("事件'"
								+ cate.getResult().getKey()
								+ "'不能完成注册, 注册url为'"
								+ definition.getMonitorUrl() + "'.\n"
								+ ExceptionUtil.getExceptionContent(e));
					}
				}
			}
		};
	}
}
